import 'package:flutter/material.dart';
import 'dart:math';

class CoupleToolsWidget extends StatelessWidget {
  const CoupleToolsWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GridView.count(
      crossAxisCount: 2,
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      mainAxisSpacing: 16.0,
      crossAxisSpacing: 16.0,
      children: [
        _buildToolCard(
          context,
          '猜拳游戏',
          Icons.back_hand,
              () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => const RockPaperScissorsPage(),
              ),
            );
          },
        ),
        _buildToolCard(
          context,
          '决定器',
          Icons.casino,
              () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => const DecisionMakerPage(),
              ),
            );
          },
        ),
        _buildToolCard(
          context,
          '情侣问答',
          Icons.question_answer,
              () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => const CoupleQuizPage(),
              ),
            );
          },
        ),
        _buildToolCard(
          context,
          '爱情计算器',
          Icons.favorite,
              () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => const LoveCalculatorPage(),
              ),
            );
          },
        ),
      ],
    );
  }

  Widget _buildToolCard(
      BuildContext context,
      String title,
      IconData icon,
      VoidCallback onTap,
      ) {
    return Card(
      elevation: 2.0,
      child: InkWell(
        onTap: onTap,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              icon,
              size: 48,
              color: Colors.pink,
            ),
            const SizedBox(height: 8),
            Text(
              title,
              style: const TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class RockPaperScissorsPage extends StatefulWidget {
  const RockPaperScissorsPage({Key? key}) : super(key: key);

  @override
  _RockPaperScissorsPageState createState() => _RockPaperScissorsPageState();
}

class _RockPaperScissorsPageState extends State<RockPaperScissorsPage> {
  String? _userChoice;
  String? _partnerChoice;
  String? _result;

  final List<String> _choices = ['石头', '剪刀', '布'];

  void _play(String choice) {
    final random = Random();
    final partnerChoice = _choices[random.nextInt(_choices.length)];

    String result;
    if (choice == partnerChoice) {
      result = '平局！';
    } else if ((choice == '石头' && partnerChoice == '剪刀') ||
        (choice == '剪刀' && partnerChoice == '布') ||
        (choice == '布' && partnerChoice == '石头')) {
      result = '你赢了！';
    } else {
      result = '对方赢了！';
    }

    setState(() {
      _userChoice = choice;
      _partnerChoice = partnerChoice;
      _result = result;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('猜拳游戏'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (_userChoice != null && _partnerChoice != null) ...[
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  Column(
                    children: [
                      const Text(
                        '你的选择',
                        style: TextStyle(fontWeight: FontWeight.bold),
                      ),
                      const SizedBox(height: 8),
                      _buildChoiceIcon(_userChoice!),
                      const SizedBox(height: 8),
                      Text(_userChoice!),
                    ],
                  ),
                  Column(
                    children: [
                      const Text(
                        '对方的选择',
                        style: TextStyle(fontWeight: FontWeight.bold),
                      ),
                      const SizedBox(height: 8),
                      _buildChoiceIcon(_partnerChoice!),
                      const SizedBox(height: 8),
                      Text(_partnerChoice!),
                    ],
                  ),
                ],
              ),
              const SizedBox(height: 24),
              Text(
                _result!,
                style: const TextStyle(
                  fontSize: 24,
                  fontWeight: FontWeight.bold,
                  color: Colors.pink,
                ),
              ),
              const SizedBox(height: 24),
              ElevatedButton(
                onPressed: () {
                  setState(() {
                    _userChoice = null;
                    _partnerChoice = null;
                    _result = null;
                  });
                },
                child: const Text('再来一次'),
              ),
            ] else ...[
              const Text(
                '选择你的手势',
                style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 24),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  _buildChoiceButton('石头', Icons.back_hand),
                  _buildChoiceButton('剪刀', Icons.content_cut),
                  _buildChoiceButton('布', Icons.panorama_wide_angle),
                ],
              ),
            ],
          ],
        ),
      ),
    );
  }

  Widget _buildChoiceButton(String choice, IconData icon) {
    return Column(
      children: [
        IconButton(
          icon: Icon(icon, size: 48),
          onPressed: () => _play(choice),
        ),
        Text(choice),
      ],
    );
  }

  Widget _buildChoiceIcon(String choice) {
    IconData icon;
    switch (choice) {
      case '石头':
        icon = Icons.back_hand;
        break;
      case '剪刀':
        icon = Icons.content_cut;
        break;
      case '布':
        icon = Icons.panorama_wide_angle;
        break;
      default:
        icon = Icons.help;
    }

    return Icon(icon, size: 48);
  }
}

class DecisionMakerPage extends StatefulWidget {
  const DecisionMakerPage({Key? key}) : super(key: key);

  @override
  _DecisionMakerPageState createState() => _DecisionMakerPageState();
}

class _DecisionMakerPageState extends State<DecisionMakerPage> {
  final TextEditingController _optionController = TextEditingController();
  final List<String> _options = [];
  String? _selectedOption;
  bool _isSpinning = false;

  void _addOption() {
    if (_optionController.text.isNotEmpty) {
      setState(() {
        _options.add(_optionController.text);
        _optionController.clear();
      });
    }
  }

  void _removeOption(int index) {
    setState(() {
      _options.removeAt(index);
    });
  }

  void _spin() {
    if (_options.length < 2) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请至少添加两个选项')),
      );
      return;
    }

    setState(() {
      _isSpinning = true;
      _selectedOption = null;
    });

    Future.delayed(const Duration(seconds: 2), () {
      final random = Random();
      setState(() {
        _selectedOption = _options[random.nextInt(_options.length)];
        _isSpinning = false;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('决定器'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _optionController,
                    decoration: const InputDecoration(
                      labelText: '添加选项',
                      hintText: '例如：看电影',
                    ),
                  ),
                ),
                IconButton(
                  icon: const Icon(Icons.add),
                  onPressed: _addOption,
                ),
              ],
            ),
            const SizedBox(height: 16),
            Expanded(
              child: _options.isEmpty
                  ? const Center(child: Text('请添加至少两个选项'))
                  : ListView.builder(
                itemCount: _options.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text(_options[index]),
                    trailing: IconButton(
                      icon: const Icon(Icons.delete),
                      onPressed: () => _removeOption(index),
                    ),
                  );
                },
              ),
            ),
            const SizedBox(height: 16),
            if (_selectedOption != null)
              Container(
                padding: const EdgeInsets.all(16.0),
                decoration: BoxDecoration(
                  color: Colors.pink.withOpacity(0.2),
                  borderRadius: BorderRadius.circular(8.0),
                ),
                child: Column(
                  children: [
                    const Text(
                      '决定结果',
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      _selectedOption!,
                      style: const TextStyle(
                        fontSize: 24,
                        fontWeight: FontWeight.bold,
                        color: Colors.pink,
                      ),
                    ),
                  ],
                ),
              ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: _isSpinning ? null : _spin,
              child: _isSpinning
                  ? const CircularProgressIndicator(color: Colors.white)
                  : const Text('开始决定'),
            ),
          ],
        ),
      ),
    );
  }
}

class CoupleQuizPage extends StatefulWidget {
  const CoupleQuizPage({Key? key}) : super(key: key);

  @override
  _CoupleQuizPageState createState() => _CoupleQuizPageState();
}

class _CoupleQuizPageState extends State<CoupleQuizPage> {
  final List<Map<String, dynamic>> _questions = [
    {
      'question': '对方最喜欢的颜色是什么？',
      'answer': '',
    },
    {
      'question': '你们的第一次约会是在哪里？',
      'answer': '',
    },
    {
      'question': '对方最喜欢的食物是什么？',
      'answer': '',
    },
    {
      'question': '对方的生日是哪一天？',
      'answer': '',
    },
    {
      'question': '你们在一起多久了？',
      'answer': '',
    },
  ];

  int _currentQuestionIndex = 0;
  final TextEditingController _answerController = TextEditingController();

  void _nextQuestion() {
    if (_answerController.text.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请输入答案')),
      );
      return;
    }

    setState(() {
      _questions[_currentQuestionIndex]['answer'] = _answerController.text;
      _answerController.clear();

      if (_currentQuestionIndex < _questions.length - 1) {
        _currentQuestionIndex++;
      } else {
        _showResults();
      }
    });
  }

  void _showResults() {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('测验结果'),
          content: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                for (final question in _questions) ...[
                  Text(
                    question['question'],
                    style: const TextStyle(fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 4),
                  Text('你的答案: ${question['answer']}'),
                  const SizedBox(height: 16),
                ],
                const Text(
                  '把这些答案分享给对方，看看你们有多了解彼此！',
                  style: TextStyle(fontStyle: FontStyle.italic),
                ),
              ],
            ),
          ),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.pop(context);
                setState(() {
                  _currentQuestionIndex = 0;
                  for (final question in _questions) {
                    question['answer'] = '';
                  }
                });
              },
              child: const Text('重新开始'),
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('情侣问答'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '问题 ${_currentQuestionIndex + 1}/${_questions.length}',
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),
            Text(
              _questions[_currentQuestionIndex]['question'],
              style: const TextStyle(fontSize: 24),
            ),
            const SizedBox(height: 24),
            TextField(
              controller: _answerController,
              decoration: const InputDecoration(
                labelText: '你的答案',
                border: OutlineInputBorder(),
              ),
              maxLines: 3,
            ),
            const SizedBox(height: 24),
            Align(
              alignment: Alignment.centerRight,
              child: ElevatedButton(
                onPressed: _nextQuestion,
                child: Text(
                  _currentQuestionIndex < _questions.length - 1 ? '下一题' : '完成',
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class LoveCalculatorPage extends StatefulWidget {
  const LoveCalculatorPage({Key? key}) : super(key: key);

  @override
  _LoveCalculatorPageState createState() => _LoveCalculatorPageState();
}

class _LoveCalculatorPageState extends State<LoveCalculatorPage> {
  final TextEditingController _name1Controller = TextEditingController();
  final TextEditingController _name2Controller = TextEditingController();
  int? _compatibilityScore;
  bool _isCalculating = false;

  void _calculateCompatibility() {
    if (_name1Controller.text.isEmpty || _name2Controller.text.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请输入两个名字')),
      );
      return;
    }

    setState(() {
      _isCalculating = true;
    });

    // 模拟计算过程
    Future.delayed(const Duration(seconds: 2), () {
      final random = Random();
      setState(() {
        // 这只是一个随机数，实际上没有任何科学依据
        _compatibilityScore = 120; // 70-100之间的随机数
        _isCalculating = false;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('爱情计算器'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _name1Controller,
              decoration: const InputDecoration(
                labelText: '你的名字',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 16),
             Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.favorite, color: Colors.pink),
                SizedBox(width: 8),
                Text('和'),
                SizedBox(width: 8),
                Icon(Icons.favorite, color: Colors.pink),
              ],
            ),
            const SizedBox(height: 16),
            TextField(
              controller: _name2Controller,
              decoration: const InputDecoration(
                labelText: '对方的名字',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 24),
            ElevatedButton(
              onPressed: _isCalculating ? null : _calculateCompatibility,
              child: _isCalculating
                  ? const CircularProgressIndicator(color: Colors.white)
                  : const Text('计算匹配度'),
            ),
            if (_compatibilityScore != null) ...[
              const SizedBox(height: 32),
              Text(
                '你们的匹配度',
                style: Theme.of(context).textTheme.headline6,
              ),
              const SizedBox(height: 16),
              Stack(
                alignment: Alignment.center,
                children: [
                  SizedBox(
                    width: 150,
                    height: 150,
                    child: CircularProgressIndicator(
                      value: _compatibilityScore! / 100,
                      strokeWidth: 10,
                      backgroundColor: Colors.grey[300],
                      valueColor: const AlwaysStoppedAnimation<Color>(Colors.pink),
                    ),
                  ),
                  Text(
                    '$_compatibilityScore%',
                    style: const TextStyle(
                      fontSize: 36,
                      fontWeight: FontWeight.bold,
                      color: Colors.pink,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 24),
              Text(
                _getCompatibilityMessage(_compatibilityScore!),
                textAlign: TextAlign.center,
                style: const TextStyle(
                  fontSize: 18,
                  fontStyle: FontStyle.italic,
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }

  String _getCompatibilityMessage(int score) {
    if (score >= 90) {
      return '天作之合！你们是命中注定的一对！';
    } else if (score >= 80) {
      return '非常般配！你们的爱情将会长久！';
    } else if (score >= 70) {
      return '很不错的匹配！你们有很多共同点！';
    } else {
      return '还算匹配！多沟通可以增进感情！';
    }
  }
}

